package com.jinlejia.erp.utils;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.bean.SaveCookieBean;
import com.weight.CustomToast;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import top.zibin.luban.LubanZ;

/**
 * @author SongJiaTai
 * @description:上传单张图片
 * @date :2019/6/23 16:33
 */
public class UploadPictureOnly {
    private Context mContext;

    public UploadPictureOnly(Context mContext) {
        this.mContext = mContext;
    }

    public synchronized  void uoloadOnlyImage (ArrayList<LubanZ.LubanZImage> files, final UploadImageCallBack callBack){
       LubanZ.get(mContext)
             .load(files)
             .asObservable()
             .flatMap(new Func1<LubanZ.LubanZImage, Observable<String>>() {
                 @Override
                 public Observable<String> call(LubanZ.LubanZImage lubanZImage) {
                     Map<String, String> header = new HashMap<>();
                     header.put("token", ACache.get(mContext).getAsString("token") == null ? ""
                             : ACache.get(mContext).getAsString("token"));
                     header.put("cookie", null == DbUtil.getDB(mContext).single()
                             .queryById(200, SaveCookieBean.class) ? ""
                             : DbUtil.getDB(mContext)
                             .single()
                             .queryById(200, SaveCookieBean.class).getCookie());
                     File file = lubanZImage.getThumbFile();
                     File originalFile = lubanZImage.getOriginalFile();
                     if (file.length()>=5242880){ //当文件超过或等于5M时，抛出异常
                         throw new IllegalArgumentException("文件过大");
                     }
                     String fileName = URLEncoder.encode(originalFile.getPath());
                     return RxUpLoad.get(mContext)
                             .url(ApiConfig.IMG_UPLOAD_2)
                             .file(file)
                             .fileName(fileName)
                             .key("uploadFileNew")
                             .header(header)
                             .asObservable();
                 }
             }).subscribeOn(Schedulers.io())
               .observeOn(AndroidSchedulers.mainThread())
               .subscribe(new Subscriber<String>() {
                   @Override
                   public void onCompleted() {

                   }

                   @Override
                   public void onError(Throwable e) {
                       e.printStackTrace();
                       if (e instanceof IOException){
                           CustomToast.showToast(mContext,"网络连接失败",1500);
                       }else {
                           CustomToast.showToast(mContext,e.getMessage(),1500);
                       }

                   }

                   @Override
                   public void onNext(String s) {
                       JSONObject jsonObject = JSON.parseObject(s);
                       JSONObject data = jsonObject.getJSONObject("data");
                       String fileName = data.getString("fileName");

                       if (jsonObject.get("code").toString().equals("200")) {
                           String url = data.getString("url");
                           if (callBack != null) {
                               callBack.onUploadSuccess(fileName, url);
                           }
                       } else {
                           if (callBack != null) {
                               callBack.onUploadonFail(jsonObject.get("code").toString());
                           }
                       }


                   }
               });
   }







    public interface UploadImageCallBack {
        void onUploadSuccess(String fileName, String serverUrl);

        void onUploadonFail(String s);
    }
}
